package cn.wolfcode.luowowo.website.interceptor;

import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.annotation.RequireLogin;
import cn.wolfcode.luowowo.website.util.CookieUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截检查
 */
public class CheckLoginInterceptor implements HandlerInterceptor {

    @Reference
    private IUserInfoRedisService userInfoRedisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserInfo userInfo = null;
        // 1、判断当前访问方法是否贴了自定义注解
        if(handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod) handler;

            String token = CookieUtil.getCookie(request);
            if(token != null){
                userInfo = userInfoRedisService.getUserInfoByToken(token);
            }

            if(handlerMethod.hasMethodAnnotation(RequireLogin.class)){
                // 2、如果贴了，看看有没有登录
                if(userInfo == null){
                    response.sendRedirect("/login.html");
                    return false;
                }
            }
        }
        // 把用户信息通过 session 共享到页面
        request.getSession().setAttribute("userInfo", userInfo);
        // 3、如果没贴，直接放行
        return true;
    }
}
